<template>
  <div style="width: 100%; overflow-y: hidden;">
    <el-form :model="form" label-width="80px">
      <el-form-item label="角色名称">
        <span>{{ form.roleName }}</span>
      </el-form-item>
      <el-form-item label="权限字符">
        <span>{{ form.roleKey }}</span>
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="form.dataScope" v-loading="deptTreeLoading" @change="selectDataScope">
          <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="form.dataScope == '2'" label="数据权限">
        <div style="height: 300px;">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
          <el-tree
            ref="deptRef"
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </div>
      </el-form-item>
    </el-form>

    <div style="margin-top: 10px; text-align: center;">
      <el-button v-loading="submitLoading" :disabled="submitLoading" type="primary" @click="submitDataScope">确 定</el-button>
      <el-button v-loading="submitLoading" :disabled="submitLoading" @click="emit('close')">取 消</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { DeptTreeOption } from '@/api/system/role/types';
import { dataScope, getRole, deptTreeSelect } from '@/api/system/role';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits(['close']);
const props = defineProps({
  roleId: {
    type: String,
    required: true
  }
});

const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptRef = ref<ElTreeInstance>();

const form = ref({
  roleId: undefined,
  roleSort: 1,
  status: '0',
  roleName: '',
  roleKey: '',
  remark: '',
  dataScope: '1',
  dataFrom: 2,
  menuIds: [],
  deptIds: []
})

/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' }
]);

/** 根据角色ID查询部门树结构 */
const deptOptions = ref<any[]>([]);
const checkedKeys = ref<any[]>([]);
const deptTreeLoading = ref(false);
const getDeptTree = async () => {
  deptTreeLoading.value = true;
  const res: any = await deptTreeSelect(props.roleId).finally(() => { deptTreeLoading.value = false; })
  console.log('获取部门：', res)

  deptOptions.value = res.data.depts;
  checkedKeys.value = res.data.checkedKeys;

  // 勾选部门数据
  await nextTick(()=> {
    deptRef.value?.setCheckedKeys(checkedKeys.value);
  });
};

/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value: boolean) => {
  for (let i = 0; i < deptOptions.value.length; i++) {
    if (deptRef.value) {
      deptRef.value.store.nodesMap[deptOptions.value[i].id].expanded = value;
    }
  }
};

/** 部门（全选/全不选） */
const handleCheckedTreeNodeAll = (value: any) => {
  deptOptions.value?.forEach((item: any) => {
    setDeptTreeCheckedKeys(item, value)
  })
};

/** 递归选择部门 */
const setDeptTreeCheckedKeys = (item: DeptTreeOption, checked: boolean) => {
  if (item.children && item.children.length > 0) {
    item.children.forEach((item: any) => {
      setDeptTreeCheckedKeys(item, checked);
    });
  } else {
    deptRef.value?.setChecked(item.id, checked, false);
  }
};

/** 选择角色权限范围触发 */
const selectDataScope = (value: string) => {
  if (value != '2') {
    deptRef.value?.setCheckedKeys([]);
  } else {
    // 勾选部门数据
    deptRef.value?.setCheckedKeys(checkedKeys.value);
  }
};

/** 获取角色信息 */
const getInfo = async ()=> {
  proxy?.$modal.loading('加载中...')
  const res = await getRole(props.roleId).finally(() => { proxy?.$modal.closeLoading() })
  console.log('获取角色详情：', res)

  Object.assign(form.value, res.data);
}

/** 提交按钮（数据权限） */
const submitLoading = ref(false);
const submitDataScope = async () => {
  // 目前被选中的部门节点
  let checkedKeys = deptRef.value?.getCheckedKeys();
  // 半选中的部门节点
  let halfCheckedKeys = deptRef.value?.getHalfCheckedKeys();
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
  }

  form.value.deptIds = checkedKeys;
  submitLoading.value = true;
  await dataScope(form.value).finally(() => { submitLoading.value = false })
  proxy?.$modal.msgSuccess('修改成功');

  emit('close')
};

onMounted(async () => {
  await getInfo()
  await getDeptTree();
})
</script>
<style scoped lang="scss">
.tree-border {
  height: calc(100% - 50px);
  width: 380px;
  overflow: auto;
}
</style>
